package com.hvgroup.modules.sanic.web;


import com.hvgroup.annotation.Log;
import com.hvgroup.annotation.rest.AnonymousGetMapping;
import com.hvgroup.annotation.rest.AnonymousPostMapping;
import com.hvgroup.modules.sanic.domain.dto.TaskResult;
import com.hvgroup.modules.sanic.service.ChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @migratedFrom Python
 * @source controllers/db_chat_api.py
 * @originalBlueprint text2sql
 * @description 控制器类，负责处理数据库问答（大模型生成 SQL 并执行）与报告查询接口。
 *              对应大模型接入后的 SQL 转换结果处理，以及相关数据报告的查询。
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/llm")
@Api(tags = "系统:会话管理")
public class DbChatController {

    private final ChatService chatService;

    /**
     * @description 执行大模型生成的 SQL，用于问答结果展示
     */
    @Log("数据问答处理大模型返回SQL语句")
    @ApiOperation("数据问答处理大模型返回SQL语句")
    @AnonymousPostMapping("/process_llm_out")
    public ResponseEntity<Object> processLlmOut(@RequestParam("llm_text") String llmText) {
        try {
            log.info("query param: {}", llmText);

            // 执行 SQL 查询（你需要实现该方法）
            Object result = chatService.processModelGeneratedSql(llmText);

            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            log.error("Error processing LLM output", e);
//            throw new MyException(SysCodeEnum.C_9999);
        }
        return null;
    }

    @GetMapping("/get_table_structure")
    public ResponseEntity<String> getTableStructure() {
        try {
            String structure = chatService.getTableStructure();
            return ResponseEntity.ok(structure);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取表结构失败: " + e.getMessage());
        }
    }


    /**
     * @description 模糊查询报告标题并返回 Markdown 内容
     */
    @Log("查询报告")
    @ApiOperation("查询报告")
    @AnonymousGetMapping("/query_guided_report")
    public ResponseEntity<Object> queryGuidedReport(@RequestParam("query_str") String queryStr) {
        try {
            String cleanedQuery = queryStr.trim().replace("\r", "");
            String result = chatService.selectReportByTitle(cleanedQuery);
            return new ResponseEntity<>(TaskResult.success(result), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询报告失败: {}", e.getMessage(), e);
//            throw new MyException(SysCodeEnum.C_9999);
        }
        return null;
    }

}
